//
//  NationwideCollectionViewCell.m
//  TodatPlay
//
//  Created by dllo on 16/9/2.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "NationwideCollectionViewCell.h"
#import "TAMacro.h"
#import "SceneTableViewCell.h"
#import "HeaderView.h"
#import "LabelView.h"
#import "ImagesView.h"
#import "FromWhereView.h"
#import "CommentView.h"
#import "SDAutoLayout.h"
#import "CDMNetTool.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
// model
#import "SceneRootClass.h"
#import "SceneObj.h"
#import "SceneCommentlist.h"
#import "SCeneCommentcountlist.h"
#import "SceneUserlist.h"
#import "SceneStorylist.h"
#import "ScenePraiseinfolist.h"
#import "ScenePraisecontainerlist.h"
#import "CommentAndPriaseVIew.h"

// 宏
#define kTableViewCellReuse @"reuse"
#define kStoryListForRow  rootClass.obj.storyList[indexPath.row]
@interface NationwideCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *nationwideTableView;
@property (nonatomic, strong) NSMutableArray *rootClassArr;
@end

@implementation NationwideCollectionViewCell
{
    NSInteger sectionNum;// 用来记载有多少个分区
}

- (NSMutableArray *)rootClassArr {
    if (_rootClassArr == nil) {
        _rootClassArr = [NSMutableArray array];
    }
    return _rootClassArr;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.nationwideTableView.delegate = self;
    self.nationwideTableView.dataSource = self;
    for (int i = 0; i < 9; i++) {
        NSString *reuse = [NSString stringWithFormat:@"reuse%d", i];
        [self.nationwideTableView registerClass:[SceneTableViewCell class] forCellReuseIdentifier:reuse];
    }
     self.nationwideTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self handleData];
    sectionNum = 1;
    [self createRefrech];

}
#pragma mark -上啦加载下拉刷新
- (void)createRefrech {
    self.nationwideTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handleLoadNewData)];
    
    self.nationwideTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handleLoadNext)];
}
- (void)handleLoadNewData {
    NSString *HTTPStr = @"http://community.api.jtwsm.cn/Story_StoryListByCity.do?platform=4&channel_from=m360_market&version=203004&source=10345";
    
    [CDMNetTool GET:HTTPStr andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        //        NSLog(@"请求成功%@", result);
        [self.rootClassArr removeAllObjects];
        sectionNum = 1;
        SceneRootClass *rootClass = [SceneRootClass modelWithDic:result];
        [self.rootClassArr addObject:rootClass];
        [self.nationwideTableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];
    [self.nationwideTableView.mj_header endRefreshing];
    
}
- (void)handleLoadNext {
    NSString *HTTPStr = @"http://community.api.jtwsm.cn/Story_StoryListByCity.do?platform=4&channel_from=m360_market&version=203004&source=10345";
    SceneRootClass *rootModel = self.rootClassArr[sectionNum - 1];
    NSString *finalURL = [HTTPStr stringByAppendingFormat:@"&listStoryId=%ld", rootModel.obj.storyList.lastObject.storyId];
    [CDMNetTool GET:finalURL andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        //        NSLog(@"请求成功%@", result);
        SceneRootClass *rootClass = [SceneRootClass modelWithDic:result];
        [self.rootClassArr addObject:rootClass];
        sectionNum ++;
        [self.nationwideTableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];
    [self.nationwideTableView.mj_footer endRefreshing];
}

#pragma mark - handleData
- (void)handleData {
    NSString *HTTPStr = @"http://community.api.jtwsm.cn/Story_StoryListByCity.do?platform=4&channel_from=m360_market&version=203004&source=10345";
    
    [CDMNetTool GET:HTTPStr andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
//                NSLog(@"请求成功%@", result);
        SceneRootClass *rootClass = [SceneRootClass modelWithDic:result];
        [self.rootClassArr addObject:rootClass];
        
        [self.nationwideTableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败%@", error);
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionNum;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SceneRootClass *rootClass = _rootClassArr[section];
    return rootClass.obj.storyList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SceneRootClass *rootClass = _rootClassArr[indexPath.section];
    NSString *contexts = kStoryListForRow.context;
    
    NSArray *imagesArr = [NSArray array];
    imagesArr = [contexts componentsSeparatedByString:@"|"];
    NSString *reuse = @"";
    for (int i = 0; i < imagesArr.count; i++) {
        reuse = [NSString stringWithFormat:@"reuse%d", i];
        
    }
    SceneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse] ;
    
    /***************** 给labelView赋值 ******************/
    cell.labelView.contentLabel.text = kStoryListForRow.comment;
    /***************** 给fromWhereView赋值 ******************/
    [cell.fromWhereView.picImageView sd_setImageWithURL:[NSURL URLWithString:kStoryListForRow.pic] placeholderImage:[UIImage imageNamed:@"wode_morenzhuban"]];
    cell.fromWhereView.desLabel.text = kStoryListForRow.projectName;
    /***************** 给ImagesView赋值 ******************/
    
    cell.imageViews.imagesArr = imagesArr;
    
    /***************** 给HeaderView赋值 ******************/
    NSString *sendUserId = [NSString stringWithFormat:@"%ld", kStoryListForRow.sendUserid];
    for (SceneUserlist *user in rootClass.obj.userList) {
        NSString *userId = [NSString stringWithFormat:@"%ld", user.userId];
        if ([userId isEqualToString:sendUserId]) {
            cell.headView.userNameLabel.text = user.userName;
            [cell.headView.picImageView sd_setImageWithURL:[NSURL URLWithString:user.userPic] placeholderImage:[UIImage imageNamed:@"wode_morentouxiang"]];
        }
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    /**=================计算时间间隔=====================*/
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 处理数据中的time
    NSString *times = kStoryListForRow.time;
    NSArray *timeArr = [NSArray array];
    timeArr = [times componentsSeparatedByString:@"T"];
    NSString *firstStr = timeArr.firstObject;
    NSString *lastStr = timeArr.lastObject;
    // 将其拼接成标准的时间格式
    NSString *dateStr = [firstStr stringByAppendingFormat:@" %@", lastStr];
    //    NSLog(@"获取的时间%@", dateStr);
    NSDate *date1 = [dateFormatter dateFromString:dateStr];
    
    NSDate *date = [NSDate date];
    
    //    NSLog(@"当前时间:%@", date);
    //计算时间间隔（单位是秒）
    
    NSTimeInterval time = [date1 timeIntervalSinceDate:date];
    
    //计算天数、时、分、秒
    
    int days = ((int)time)/(3600*24);
    
    int hours = ((int)time)%(3600*24)/3600;
    
    int minutes = ((int)time)%(3600*24)%3600/60;
//    
//    int seconds = ((int)time)%(3600*24)%3600%60;
//    
//    NSString *dateContent = [[NSString alloc] initWithFormat:@"仅剩%i天%i小时%i分%i秒",days,hours,minutes,seconds];
//    
//    NSLog(@"%@", dateContent);
//    NSLog(@"days = %d", minutes);
    /**=================计算时间间隔结束=====================*/
    if (-days > 0) {
        cell.headView.timeLabel.text = [NSString stringWithFormat:@"%d天前", -days];
    } else if (-hours > 0 && -days == 0) {
        cell.headView.timeLabel.text = [NSString stringWithFormat:@"%d小时前", -hours];
    } else if (-minutes > 0 && -days == 0 && -hours == 0){
        cell.headView.timeLabel.text = [NSString stringWithFormat:@"%d分钟前", -minutes];
    }
    /***************** 给commentView赋值 ******************/
    
    
    
    
    NSString *storyId = [NSString stringWithFormat:@"%ld", kStoryListForRow.storyId];
    NSMutableArray *praiseArr = [NSMutableArray array];
    for (ScenePraiseinfolist *list in rootClass.obj.praiseInfoList) {
        if ([storyId isEqualToString:[NSString stringWithFormat:@"%ld", list.storyId]]) {
            [praiseArr addObject:list];
            
        }
    }
    
    NSMutableArray *commentArr = [NSMutableArray array];
    for (SceneCommentlist *list in rootClass.obj.commentList) {
        if ([storyId isEqualToString:[NSString stringWithFormat:@"%ld", list.storyId]]) {
            [commentArr addObject:list];
        }
    }
    [cell.commentAndPraiseView setupWithLikeItemsArray:praiseArr commentItemsArray:commentArr];
    cell.commentAndPraiseView.userList = rootClass.obj.userList;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:(self.contentView.bounds.size.width - 10) tableView:self.nationwideTableView];
}






@end
